﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QLVatTu.Class;
using System.Globalization;

namespace QLVatTu.NghiepVu
{
    public partial class frmPhieuTraDonViSanXuat : Form
    {
        KetNoiDB cn = new KetNoiDB();
        public string MaPhieuNhapTra = "";

        public frmPhieuTraDonViSanXuat()
        {
            InitializeComponent();
        }

        private void loadData()
        {
            cbbDoiTac.DataSource = cn.getTable("select * from tbl_DoiTac where DonViSanXuat=1");
            cbbDoiTac.DisplayMember = "TenDoiTac";
            cbbDoiTac.ValueMember = "MaDoiTac";

            cbbKhoNhap.DataSource = cn.getTable("select * from tbl_Kho");
            cbbKhoNhap.DisplayMember = "TenKho";
            cbbKhoNhap.ValueMember = "MaKho";

            cbbLoaiPhieu.DataSource = cn.getTable("select * from tbl_LoaiPhieu where MaLoaiPhieu='LP002'");
            cbbLoaiPhieu.DisplayMember = "TenLoaiPhieu";
            cbbLoaiPhieu.ValueMember = "MaLoaiPhieu";

            cbbCongTrinhDuAn.DataSource = cn.getTable("select * from tbl_CongTrinhDuAn");
            cbbCongTrinhDuAn.DisplayMember = "TenCongTrinhDuAn";
            cbbCongTrinhDuAn.ValueMember = "MaCongTrinhDuAn";

            cbbXacNhan.SelectedIndex = 0;

            DataTable dt = new DataTable();
            dt = cn.getTable("select SoPhieu from tbl_PhieuXuatKho where MaLoaiPhieu='LP003' and XacNhan=1");
            DataRow dr = dt.NewRow();
            dr["SoPhieu"] = "---Danh sách phiếu---";
            dt.Rows.InsertAt(dr, 0);
            cbbPhieuXuat.DataSource = dt;
            cbbPhieuXuat.DisplayMember = "SoPhieu";
            cbbPhieuXuat.ValueMember = "SoPhieu";

            string sql = "";

            if (MaPhieuNhapTra == "")
            {
                //Thêm
                txtSoPhieu.Text = cn.SinhMa("SoPhieu", "tbl_PhieuNhapKho", "PN");
            }
            else
            {
                //Sửa
                txtSoPhieu.Text = MaPhieuNhapTra;
                btnLuu.Enabled = true;
                cbbPhieuXuat.Enabled = false;
                btnChon.Enabled = false;
                ckbChonHet.Enabled = false;
                dgvVatTuXuat.Enabled = false;

                sql = "select * from tbl_PhieuNhapKho where SoPhieu='"+MaPhieuNhapTra+"'";
                dt = cn.getTable(sql);
                if (dt.Rows.Count > 0)
                {
                    dtpNgayLap.Value = DateTime.Parse(dt.Rows[0]["NgayNhap"].ToString());
                    cbbDoiTac.SelectedValue = dt.Rows[0]["MaDoiTac"].ToString();
                    cbbKhoNhap.SelectedValue = dt.Rows[0]["MaKho"].ToString();
                    txtNhanVien.Text = dt.Rows[0]["NguoiNhan"].ToString();
                    txtDienGiai.Text = dt.Rows[0]["DienGiai"].ToString();
                    cbbLoaiPhieu.SelectedValue = dt.Rows[0]["MaLoaiPhieu"].ToString();
                    cbbCongTrinhDuAn.SelectedValue = dt.Rows[0]["MaCongTrinhDuAn"].ToString();

                    string MaPhieuXuat = dt.Rows[0]["MaPhieuXuat"].ToString();
                    cbbPhieuXuat.SelectedValue = MaPhieuXuat;

                    //loa dgvVatTuXuat khi sửa
                    load_dgvVatTuXuat(MaPhieuXuat);

                    //load dgvChiTietNhap
                    sql = @"SELECT     dbo.tbl_ChiTietPhieuNhap.MaVatTu, dbo.tbl_VatTu.TenVatTu, dbo.tbl_ChiTietPhieuNhap.MaDonViTinh, dbo.tbl_DonViTinh.TenDonViTinh, 
                                                  dbo.tbl_ChiTietPhieuNhap.SoLuong, tbl_ChiTietPhieuNhap.SoLuongPhePham
                            FROM         dbo.tbl_ChiTietPhieuNhap INNER JOIN
                                                  dbo.tbl_DonViTinh ON dbo.tbl_ChiTietPhieuNhap.MaDonViTinh = dbo.tbl_DonViTinh.MaDonViTinh INNER JOIN
                                                  dbo.tbl_VatTu ON dbo.tbl_ChiTietPhieuNhap.MaVatTu = dbo.tbl_VatTu.MaVatTu
                            WHERE     dbo.tbl_ChiTietPhieuNhap.SoPhieu='" + MaPhieuNhapTra + "'";
                    dt = cn.getTable(sql);
                    int stt = 0;
                    if (dt.Rows.Count > 0)
                    {
                        foreach (DataRow drct in dt.Rows)
                        {
                            stt++;

                            DataGridViewRow dgvRowChiTiet = (DataGridViewRow)dgvChiTietPhieuNhap.Rows[0].Clone();
                            dgvRowChiTiet.Cells[1].Value = stt;
                            dgvRowChiTiet.Cells[2].Value = drct["TenVatTu"].ToString();
                            dgvRowChiTiet.Cells[3].Value = drct["TenDonViTinh"].ToString();

                            float SoLuongDaCap = 0;
                            sql = @"SELECT     SUM(dbo.tbl_ChiTietPhieuXuat.SoLuong) AS SoLuongDaCap
                            FROM         dbo.tbl_ChiTietPhieuXuat INNER JOIN
                                                  dbo.tbl_PhieuXuatKho ON dbo.tbl_ChiTietPhieuXuat.SoPhieu = dbo.tbl_PhieuXuatKho.SoPhieu
                            WHERE    dbo.tbl_PhieuXuatKho.SoPhieu = '" + cbbPhieuXuat.SelectedValue.ToString() + "' AND dbo.tbl_ChiTietPhieuXuat.MaVatTu = '" + drct["MaVatTu"].ToString() + @"'
                            GROUP BY dbo.tbl_ChiTietPhieuXuat.MaVatTu";
                            DataTable dtSoLuongDaCap = cn.getTable(sql);
                            if (dtSoLuongDaCap.Rows.Count == 1)
                            {
                                SoLuongDaCap = float.Parse(dtSoLuongDaCap.Rows[0]["SoLuongDaCap"].ToString());
                            }
                            dgvRowChiTiet.Cells[4].Value = SoLuongDaCap;

                            float SoLuongDaTraTruocKhiLapPhieu = 0;
                            sql = @"SELECT     SUM(dbo.tbl_ChiTietPhieuNhap.SoLuong) AS SoLuongDaTra
                                    FROM         dbo.tbl_ChiTietPhieuNhap INNER JOIN
                                                          dbo.tbl_PhieuNhapKho ON dbo.tbl_ChiTietPhieuNhap.SoPhieu = dbo.tbl_PhieuNhapKho.SoPhieu
                                    WHERE   tbl_PhieuNhapKho.SoPhieu!='" + MaPhieuNhapTra + "' and tbl_PhieuNhapKho.XacNhan=1 and dbo.tbl_PhieuNhapKho.MaPhieuXuat = '" + cbbPhieuXuat.SelectedValue.ToString() + "' and tbl_PhieuNhapKho.MaLoaiPhieu='LP002' AND dbo.tbl_ChiTietPhieuNhap.MaVatTu = '" + drct["MaVatTu"].ToString() + @"'
                                    GROUP BY dbo.tbl_ChiTietPhieuNhap.MaVatTu";
                            dt = cn.getTable(sql);
                            if (dt.Rows.Count > 0) SoLuongDaTraTruocKhiLapPhieu = float.Parse(dt.Rows[0]["SoLuongDaTra"].ToString());
                            dgvChiTietPhieuNhap.Columns[5].HeaderText="Số lượng đã trả trước khi lập phiếu";
                            dgvRowChiTiet.Cells[5].Value = SoLuongDaTraTruocKhiLapPhieu;

                            double SoLuongCoTheTra = Math.Round(SoLuongDaCap - SoLuongDaTraTruocKhiLapPhieu,2);
                            dgvRowChiTiet.Cells[6].Value = SoLuongCoTheTra;
                            dgvRowChiTiet.Cells[7].Value = drct["SoLuong"].ToString();
                            dgvRowChiTiet.Cells[8].Value = drct["SoLuongPhePham"].ToString();
                            dgvRowChiTiet.Cells[9].Value = drct["MaVatTu"].ToString();
                            dgvRowChiTiet.Cells[10].Value = drct["MaDonViTinh"].ToString();
                            dgvChiTietPhieuNhap.Rows.Add(dgvRowChiTiet);
                        }
                    }
                }
            }
        }

        private void frmPhieuTraDonViSanXuat_Load(object sender, EventArgs e)
        {
            if (cn.KetNoi())
            {
                loadData();
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //Hàm load dgvVatTuXuat
        private void load_dgvVatTuXuat(string MaPhieuXuat)
        {
            cbbCongTrinhDuAn.SelectedValue = cn.LayDuLieu("select MaCongTrinhDuAn from tbl_PhieuXuatKho where SoPhieu='"+MaPhieuXuat+"'");
            cbbDoiTac.SelectedValue = cn.LayDuLieu("select MaDoiTac from tbl_PhieuXuatKho where SoPhieu='"+MaPhieuXuat+"'");
            string sql = @"SELECT  row_number() over(order by tbl_ChiTietPhieuXuat.SoPhieu) as STT,  dbo.tbl_ChiTietPhieuXuat.MaVatTu, dbo.tbl_VatTu.TenVatTu, dbo.tbl_ChiTietPhieuXuat.MaDonViTinh, dbo.tbl_DonViTinh.TenDonViTinh, 
                                       dbo.tbl_ChiTietPhieuXuat.SoLuong
                               FROM         dbo.tbl_ChiTietPhieuXuat INNER JOIN
                                                      dbo.tbl_DonViTinh ON dbo.tbl_ChiTietPhieuXuat.MaDonViTinh = dbo.tbl_DonViTinh.MaDonViTinh INNER JOIN
                                                      dbo.tbl_VatTu ON dbo.tbl_ChiTietPhieuXuat.MaVatTu = dbo.tbl_VatTu.MaVatTu
                               WHERE     dbo.tbl_ChiTietPhieuXuat.SoPhieu = '" + MaPhieuXuat + "'";
            DataTable tbl = cn.getTable(sql);
            dgvVatTuXuat.Rows.Clear();
            ckbChonHet.Checked = false;
            dgvChiTietPhieuNhap.Rows.Clear();
            if (tbl.Rows.Count > 0)
            {
                foreach (DataRow dr in tbl.Rows)
                {
                    DataGridViewRow dtgRow = (DataGridViewRow)dgvVatTuXuat.Rows[0].Clone();
                    dtgRow.Cells[1].Value = dr["STT"].ToString();
                    dtgRow.Cells[2].Value = dr["TenVatTu"].ToString();
                    dtgRow.Cells[3].Value = dr["TenDonViTinh"].ToString();

                    float SoLuongDaCap = 0;
                    sql = @"SELECT     SUM(dbo.tbl_ChiTietPhieuXuat.SoLuong) AS SoLuongDaCap
                            FROM         dbo.tbl_ChiTietPhieuXuat INNER JOIN
                                                  dbo.tbl_PhieuXuatKho ON dbo.tbl_ChiTietPhieuXuat.SoPhieu = dbo.tbl_PhieuXuatKho.SoPhieu
                            WHERE     dbo.tbl_PhieuXuatKho.SoPhieu = '" + cbbPhieuXuat.SelectedValue.ToString() + "' AND dbo.tbl_ChiTietPhieuXuat.MaVatTu = '" + dr["MaVatTu"].ToString() + @"'
                            GROUP BY dbo.tbl_ChiTietPhieuXuat.MaVatTu";
                    DataTable dtSoLuongDaCap = cn.getTable(sql);
                    if (dtSoLuongDaCap.Rows.Count == 1)
                    {
                        SoLuongDaCap = float.Parse(dtSoLuongDaCap.Rows[0]["SoLuongDaCap"].ToString());
                    }

                    dtgRow.Cells[4].Value=SoLuongDaCap;

                    float SoLuongDaNhap = 0;
                    sql = @"SELECT     SUM(dbo.tbl_ChiTietPhieuNhap.SoLuong) AS SoLuongDaNhap
                            FROM         dbo.tbl_ChiTietPhieuNhap INNER JOIN
                                                  dbo.tbl_PhieuNhapKho ON dbo.tbl_ChiTietPhieuNhap.SoPhieu = dbo.tbl_PhieuNhapKho.SoPhieu
                            WHERE     dbo.tbl_PhieuNhapKho.MaPhieuXuat = '" + cbbPhieuXuat.SelectedValue.ToString() + "' and tbl_PhieuNhapKho.XacNhan=1 AND dbo.tbl_ChiTietPhieuNhap.MaVatTu = '" + dr["MaVatTu"].ToString() + @"'
                            GROUP BY dbo.tbl_ChiTietPhieuNhap.MaVatTu";
                    DataTable dtSoLuong = cn.getTable(sql);
                    if (dtSoLuong.Rows.Count == 1)
                    {
                        SoLuongDaNhap = float.Parse(dtSoLuong.Rows[0]["SoLuongDaNhap"].ToString());
                    }
                    dtgRow.Cells[5].Value = SoLuongDaNhap;

                    dtgRow.Cells[6].Value = dr["MaVatTu"].ToString();
                    dtgRow.Cells[7].Value = dr["MaDonViTinh"].ToString();
                    dgvVatTuXuat.Rows.Add(dtgRow);
                }
            }
            foreach (DataGridViewRow dgvr in dgvVatTuXuat.Rows)
            {
                if (dgvr.IsNewRow) continue;
                dgvr.Cells[0].Value = ckbChonHet.Checked;
            }
        }
        private void cbbPhieuXuat_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbbPhieuXuat.SelectedValue != null)
            {
                load_dgvVatTuXuat(cbbPhieuXuat.SelectedValue.ToString());
            }
            else
            {
                dgvVatTuXuat.Rows.Clear();
            }
        }

        private void dgvVatTuXuat_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvVatTuXuat.RowCount > 0 && e.ColumnIndex == 0)
            {
                if (!dgvVatTuXuat.Rows[e.RowIndex].IsNewRow && dgvVatTuXuat.Rows[e.RowIndex].Cells[0].Value != null)
                {
                    bool Checked = bool.Parse(dgvVatTuXuat.Rows[e.RowIndex].Cells[0].Value.ToString());
                    dgvVatTuXuat.Rows[e.RowIndex].Cells[0].Value = !Checked;
                }
            }
        }

        private void load_dgvChiTietPhieuNhapTra()
        {
            dgvChiTietPhieuNhap.Rows.Clear();
            int STT = 0;

            foreach (DataGridViewRow dgvr in dgvVatTuXuat.Rows)
            {
                if (dgvr.IsNewRow) continue;
                if (dgvr.Cells[0].Value != null && bool.Parse(dgvr.Cells[0].Value.ToString()) == true && dgvr.Cells["VatTu"].Value != null)
                {
                    STT++;
                    DataGridViewRow dtgRowPN=(DataGridViewRow)dgvChiTietPhieuNhap.Rows[0].Clone();
                    dtgRowPN.Cells[1].Value=STT;
                    dtgRowPN.Cells[2].Value=dgvr.Cells["VatTu"].Value.ToString();
                    dtgRowPN.Cells[3].Value=dgvr.Cells["DonViTinh"].Value.ToString();
                    dtgRowPN.Cells[4].Value=dgvr.Cells["SoLuongDaCap"].Value.ToString();
                    dtgRowPN.Cells[5].Value=dgvr.Cells["SoLuongDaTra"].Value.ToString();

                    double SoLuongCoTheTra =Math.Round((float.Parse(dgvr.Cells["SoLuongDaCap"].Value.ToString()) - float.Parse(dgvr.Cells["SoLuongDaTra"].Value.ToString())),2);
                    if (SoLuongCoTheTra <= 0)
                    {
                        continue;
                    }
                    else
                    {
                        dtgRowPN.Cells[6].Value = SoLuongCoTheTra;
                    }

                    dtgRowPN.Cells[9].Value=dgvr.Cells["MaVatTu"].Value.ToString();
                    dtgRowPN.Cells[10].Value=dgvr.Cells["MaDonViTinh"].Value.ToString();
                    dgvChiTietPhieuNhap.Rows.Add(dtgRowPN);

                    foreach (DataGridViewRow dgvrCTN in dgvChiTietPhieuNhap.Rows)
                    {
                        if (dgvrCTN.IsNewRow) continue;
                        dgvrCTN.Cells[0].Value = false;
                    }
                }
            }
        }

        bool IsValid()
        {
            bool kt = true;

            

           if (txtNhanVien.Text == "")
            {
                MessageBox.Show("Bạn chưa nhập tên nhân viên.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtNhanVien.Focus();
                return false;
            }

           else if (cbbPhieuXuat.SelectedValue.ToString() == "---Danh sách phiếu---")
           {
               MessageBox.Show("Bạn chưa chọn phiếu xuất.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
               cbbPhieuXuat.Focus();
               return false;
           }

           else if (cbbPhieuXuat.SelectedIndex > 0)
           {
               string sql = "select NgayXuat from tbl_PhieuXuatKho where SoPhieu='" + cbbPhieuXuat.SelectedValue.ToString() + "'";
               DateTime dtNgayXuat = DateTime.Parse(cn.LayDuLieu(sql));

               if (dtpNgayLap.Value < dtNgayXuat || dtpNgayLap.Value > DateTime.Now)
               {
                   MessageBox.Show("Ngày lập phiếu không hợp lý", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   dtpNgayLap.Focus();
                   kt = false;
               }
           }

            foreach (DataGridViewRow dgvr in dgvChiTietPhieuNhap.Rows)
            {
                if (dgvr.IsNewRow) continue;

                if (dgvr.Cells["SoLuongCT"].Value == null && dgvr.Cells["SoLuongPhePham"].Value == null)
                {
                    dgvr.Cells["SoLuongCT"].ErrorText = "Lỗi: " + dgvChiTietPhieuNhap.Columns[dgvr.Cells["SoLuongCT"].ColumnIndex].HeaderText + " chưa được nhập ";
                    dgvr.Cells["SoLuongPhePham"].ErrorText = "Lỗi: " + dgvChiTietPhieuNhap.Columns[dgvr.Cells["SoLuongPhePham"].ColumnIndex].HeaderText + " chưa được nhập";
                    kt = false;
                }
                else
                {
                    //dgvr.Cells["SoLuongCT"].ErrorText = "";
                    //dgvr.Cells["SoLuongPhePham"].ErrorText = "";

                    string strSoLuong;
                    double SoLuongCT = 0;
                    string strSoLuongPhePham;
                    double SoLuongPhePhamCT = 0;
                    float SoLuongCoTheTraCT = 0;

                    //Kiểm tra số lượng
                    if (dgvr.Cells["SoLuongCT"].Value.ToString().Contains(','))
                    {
                        strSoLuong = dgvr.Cells["SoLuongCT"].Value.ToString().Replace(',', '.');
                    }
                    else
                    {
                        strSoLuong = dgvr.Cells["SoLuongCT"].Value.ToString();
                    }
                    double.TryParse(strSoLuong, out SoLuongCT);
                    //SoLuong = double.Parse(strSoLuong);

                    //Kiểm tra số lượng phế phẩm
                    if (dgvr.Cells["SoLuongPhePham"].Value.ToString().Contains(','))
                    {
                        strSoLuongPhePham = dgvr.Cells["SoLuongPhePham"].Value.ToString().Replace(',', '.');
                    }
                    else
                    {
                        strSoLuongPhePham = dgvr.Cells["SoLuongPhePham"].Value.ToString();
                    }
                    double.TryParse(strSoLuongPhePham, out SoLuongPhePhamCT);

                    //Số lượng có thể trả lại
                    SoLuongCoTheTraCT = float.Parse(dgvr.Cells["SoLuongCoTheTraCT"].Value.ToString());

                    if (SoLuongCT < 0)
                    {
                        dgvr.Cells["SoLuongCT"].ErrorText = "Lỗi: " + dgvChiTietPhieuNhap.Columns[dgvr.Cells["SoLuongCT"].ColumnIndex].HeaderText + " trả về không âm.";
                        kt = false;
                    }
                    else
                    {
                        dgvr.Cells["SoLuongCT"].ErrorText = "";
                        if (SoLuongPhePhamCT < 0)
                        {
                            dgvr.Cells["SoLuongPhePham"].ErrorText = "Lỗi: " + dgvChiTietPhieuNhap.Columns[dgvr.Cells["SoLuongPhePham"].ColumnIndex].HeaderText + " trả về không âm.";
                            kt = false;
                        }
                        else
                        {
                            dgvr.Cells["SoLuongPhePham"].ErrorText = "";
                        }
                       
                    }

                    if (SoLuongCT == 0 && SoLuongPhePhamCT == 0)
                    {
                        dgvr.Cells["VatTuCT"].ErrorText = "Lỗi: " + dgvChiTietPhieuNhap.Columns[dgvr.Cells["VatTuCT"].ColumnIndex].HeaderText + " không trả về. xóa khỏi danh sách";
                        kt = false;
                    }
                    else
                    {
                        dgvr.Cells["VatTuCT"].ErrorText = "";

                    }
                    if (SoLuongCT > SoLuongCoTheTraCT)
                    {
                        dgvr.Cells["SoLuongCT"].ErrorText = "Lỗi: " + dgvChiTietPhieuNhap.Columns[dgvr.Cells["SoLuongCT"].ColumnIndex].HeaderText + " trả về không hợp lý ";
                        dgvr.Cells["SoLuongPhePham"].ErrorText = "Lỗi: " + dgvChiTietPhieuNhap.Columns[dgvr.Cells["SoLuongPhePham"].ColumnIndex].HeaderText + " trả về không hợp lý";
                        kt = false;
                    }
                    else
                    {
                        //dgvr.Cells["SoLuongCT"].ErrorText = "";
                        //dgvr.Cells["SoLuongPhePham"].ErrorText = "";
                        if (SoLuongCT == SoLuongCoTheTraCT && SoLuongPhePhamCT != 0 || SoLuongPhePhamCT >= SoLuongCoTheTraCT)
                        {
                            dgvr.Cells["SoLuongPhePham"].ErrorText = "Lỗi: " + dgvChiTietPhieuNhap.Columns[dgvr.Cells["SoLuongPhePham"].ColumnIndex].HeaderText + " trả về không hợp lí";
                            kt = false;
                        }
                        else
                        {
                            //dgvr.Cells["SoLuongPhePham"].ErrorText = "";
                        }
                    }
                }
            }
            return kt;
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (IsValid())
            {
                string SoPhieu = txtSoPhieu.Text;
                string NgayNhap = dtpNgayLap.Value.ToString("yyyy-MM-dd");
                string MaDoiTac = cbbDoiTac.SelectedValue.ToString();
                string MaKho = cbbKhoNhap.SelectedValue.ToString();
                string NguoiNhan = txtNhanVien.Text;
                string DienGiai = txtDienGiai.Text;
                string MaLoaiPhieu = cbbLoaiPhieu.SelectedValue.ToString();
                string MaCongTrinhDuAn = cbbCongTrinhDuAn.SelectedValue.ToString();
                string MaPhieuXuat = cbbPhieuXuat.SelectedValue.ToString();
                byte XacNhan = 0;
                if (cbbXacNhan.Text == "Đã xác nhận")
                {
                    XacNhan = 1;
                }

                string MaVatTu;
                string MaDonViTinh;
                double SoLuong;
                double SoLuongPhePham;
                string strSoLuong;
                string strSoLuongPhePham;

                if (MaPhieuNhapTra == "")
                {
                    cn.Insert_Table("tbl_PhieuNhapKho", "SoPhieu,NgayNhap,MaDoiTac,MaKho,NguoiNhan,DienGiai,MaLoaiPhieu,MaCongTrinhDuAn,MaPhieuXuat,XacNhan", "'" + SoPhieu + "','" + NgayNhap + "','" + MaDoiTac + "','" + MaKho + "',N'" + NguoiNhan + "',N'" + DienGiai + "','" + MaLoaiPhieu + "','" + MaCongTrinhDuAn + "','"+MaPhieuXuat+"','"+XacNhan+"'");

                    foreach (DataGridViewRow dgvr in dgvChiTietPhieuNhap.Rows)
                    {
                        if (dgvr.IsNewRow) continue;
                        MaVatTu = dgvr.Cells["MaVatTuCT"].Value.ToString();
                        MaDonViTinh = dgvr.Cells["MaDonViTinhCT"].Value.ToString();

                        //Kiểm tra số lượng
                        if (dgvr.Cells["SoLuongCT"].Value.ToString().Contains(','))
                        {
                            strSoLuong = dgvr.Cells["SoLuongCT"].Value.ToString().Replace(',', '.');
                        }
                        else
                        {
                            strSoLuong = dgvr.Cells["SoLuongCT"].Value.ToString();
                        }
                        double.TryParse(strSoLuong, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out SoLuong);

                        //Kiểm tra số lượng phế phẩm
                        if (dgvr.Cells["SoLuongPhePham"].Value.ToString().Contains(','))
                        {
                            strSoLuongPhePham = dgvr.Cells["SoLuongPhePham"].Value.ToString().Replace(',', '.');
                        }
                        else
                        {
                            strSoLuongPhePham = dgvr.Cells["SoLuongPhePham"].Value.ToString();
                        }
                        double.TryParse(strSoLuongPhePham, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out SoLuongPhePham);

                        cn.Insert_Table("tbl_ChiTietPhieuNhap", "SoPhieu,MaVatTu,MaDonViTinh,SoLuong,SoLuongPhePham", "'" + SoPhieu + "','" + MaVatTu + "','" + MaDonViTinh + "','" + SoLuong.ToString().Replace(",", ".") + "','" + SoLuongPhePham.ToString().Replace(",", ".") + "'");

                        if (XacNhan == 1)
                        {
                            cn.Insert_Table("tbl_LuuKho", "SoPhieu,MaKho,MaVatTu,SoLuong,SoLuongPhePham,NgayCapNhat", "'" + SoPhieu + "','" + MaKho + "','" + MaVatTu + "','" + SoLuong.ToString().Replace(",", ".") + "','" + SoLuongPhePham.ToString().Replace(",", ".") + "','" + NgayNhap + "'");
                        }
                    }
                    HangSo.Luu_Hanh_Dong(HangSo.TenDangNhap, HangSo.TenQuyenHan, HangSo.TenNguoiDung, "Thêm phiếu trả đơn vị sản xuất.");
                    MessageBox.Show("Cập nhật thành công");
                }
                else
                {
                    cn.Update_Table("tbl_PhieuNhapKho", "NgayNhap='" + NgayNhap + "',MaKho='"+MaKho+"',NguoiNhan=N'" + NguoiNhan + "',DienGiai=N'" + DienGiai + "',XacNhan='"+XacNhan+"'", "SoPhieu='" + SoPhieu + "'");
                    cn.Delete_Table("tbl_ChiTietPhieuNhap", "SoPhieu='" + SoPhieu + "'");
                    cn.Delete_Table("tbl_LuuKho", "SoPhieu='" + SoPhieu + "'");

                    foreach (DataGridViewRow dgvr in dgvChiTietPhieuNhap.Rows)
                    {
                        if (dgvr.IsNewRow) continue;

                        MaVatTu = dgvr.Cells["MaVatTuCT"].Value.ToString();
                        MaDonViTinh = dgvr.Cells["MaDonViTinhCT"].Value.ToString();

                        //Kiểm tra số lượng
                        if (dgvr.Cells["SoLuongCT"].Value.ToString().Contains(','))
                        {
                            strSoLuong = dgvr.Cells["SoLuongCT"].Value.ToString().Replace(',', '.');
                        }
                        else
                        {
                            strSoLuong = dgvr.Cells["SoLuongCT"].Value.ToString();
                        }
                        double.TryParse(strSoLuong, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out SoLuong);

                        //Kiểm tra số lượng phế phẩm
                        if (dgvr.Cells["SoLuongPhePham"].Value.ToString().Contains(','))
                        {
                            strSoLuongPhePham = dgvr.Cells["SoLuongPhePham"].Value.ToString().Replace(',', '.');
                        }
                        else
                        {
                            strSoLuongPhePham = dgvr.Cells["SoLuongPhePham"].Value.ToString();
                        }
                        double.TryParse(strSoLuongPhePham, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out SoLuongPhePham);

                        cn.Insert_Table("tbl_ChiTietPhieuNhap", "SoPhieu,MaVatTu,MaDonViTinh,SoLuong,SoLuongPhePham", "'" + SoPhieu + "','" + MaVatTu + "','" + MaDonViTinh + "','" + SoLuong.ToString().Replace(",", ".") + "','" + SoLuongPhePham.ToString().Replace(",", ".") + "'");

                        if (XacNhan == 1)
                        {
                            cn.Insert_Table("tbl_LuuKho", "SoPhieu,MaKho,MaVatTu,SoLuong,SoLuongPhePham,NgayCapNhat", "'" + SoPhieu + "','" + MaKho + "','" + MaVatTu + "','" + SoLuong.ToString().Replace(",", ".") + "','" + SoLuongPhePham.ToString().Replace(",", ".") + "','" + NgayNhap + "'");
                        }
                    }
                    HangSo.Luu_Hanh_Dong(HangSo.TenDangNhap, HangSo.TenQuyenHan, HangSo.TenNguoiDung, "Sửa phiếu nhập mua.");
                    MessageBox.Show("Cập nhật thành công");
                }
                this.Close();
            }
        }

        private void ckbChonHet_Click(object sender, EventArgs e)
        {
            if (dgvVatTuXuat.RowCount > 0)
            {
                foreach (DataGridViewRow dgvr in dgvVatTuXuat.Rows)
                {
                    if (dgvr.IsNewRow) continue;
                    dgvr.Cells[0].Value = ckbChonHet.Checked;
                }
                dgvVatTuXuat.EndEdit();
            }
        }

        private void btnChon_Click(object sender, EventArgs e)
        {
            load_dgvChiTietPhieuNhapTra();
        }

        private void btnXoaChon_Click(object sender, EventArgs e)
        {
            if (dgvChiTietPhieuNhap.RowCount > 1)
            {
                for (int i = dgvChiTietPhieuNhap.Rows.Count-1; i >= 0; i--)
                {
                    if ((bool)dgvChiTietPhieuNhap.Rows[i].Cells[0].FormattedValue)
                    {
                        dgvChiTietPhieuNhap.Rows.RemoveAt(i);
                    }
                }
            }
        }
    }
}
